#!/bin/sh
#
# Miredo - Teredo IPv6 tunnelling
#
# Init script for miredo client.
#
# Written by Fridrich von Stauffenberg <cancellor2@gmail.com>
# Based on tor's init script by Marco Bonetti <sid77@slackware.it>

PIDFILE=/var/run/miredo.pid
DAEMON=/usr/sbin/miredo

miredo_start() {
  echo "Starting Miredo: $DAEMON"
  $DAEMON
}

miredo_stop() {
  echo -n "Stopping Miredo... "
  PID=$(cat $PIDFILE 2>/dev/null)
  if [ -z "$PID" ]; then
    echo "not running."
    exit 0
  fi
  if kill -15 $PID; then
    echo "stopped."
  else
    sleep 1
    if kill -9 $PID; then
      echo "killed."
    else
      echo "error!"
      exit 1
    fi
  fi
}

miredo_reload() {
  echo -n "Reloading Miredo... "
  PID=$(cat $PIDFILE 2>/dev/null)
  if [ -z "$PID" ]; then
    echo "not running."
    exit 0
  fi
  if kill -1 $PID; then
    echo "reloaded."
  else
    echo "error!"
    exit 1
  fi
}

miredo_status() {
  PID=$(cat $PIDFILE 2>/dev/null)
  if [ -z "$PID" ]; then
    echo "Not running."
    exit 1
  elif kill -0 $PID; then
    echo "Running with PID $PID."
    exit 0
  else
    echo "PID file $PIDFILE present, but PID $PID is not running."
    exit 1
  fi
}

case "$1" in
  start)
    miredo_start
  ;;
  stop)
    miredo_stop
  ;;
  restart)
    miredo_stop
    sleep 1
    miredo_start
  ;;
  reload)
    miredo_reload
  ;;
  status)
    miredo_status
  ;;
  *)
    echo "Usage: $0 (start|stop|restart|reload|status)"
  ;;
esac
